package com.xiaotao.util;

import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;

import java.text.ParseException;
import java.util.Map;

public class JwtUtil {
    private static final String secretString = "token!Q2W#E$RWtoken!Q2W#E$RWtoken!Q2W#E$RW";
    public static String getToken(Map map) throws JOSEException {
        JWSHeader build = new JWSHeader.Builder(JWSAlgorithm.HS256).type(JOSEObjectType.JWT).build();
        Payload payload = new Payload(map);
        MACSigner macSigner = new MACSigner(secretString);
        JWSObject jwsObject = new JWSObject(build, payload);
        jwsObject.sign(macSigner);
        String token = jwsObject.serialize();
        return token;
    }
    public static boolean verify(String jwt) throws ParseException, JOSEException {
        JWSObject parse = JWSObject.parse(jwt);
        MACVerifier macVerifier = new MACVerifier(secretString);
        boolean verify = parse.verify(macVerifier);
        return verify;
    }
    public static Map map(String jwt) throws ParseException {
        JWSObject parse = JWSObject.parse(jwt);
        Payload payload = parse.getPayload();
        Map<String, Object> jsonObject = payload.toJSONObject();
        return jsonObject;
    }
    public static Integer getUserId(String token) throws Exception {
        JWSObject parse = JWSObject.parse(token);
        Payload payload = parse.getPayload();
        Map<String, Object> jsonObject = payload.toJSONObject();
        Integer userId = Integer.parseInt(jsonObject.get("id").toString());
        return userId;
    }
}
